package com.miku.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miku.blog.domain.UserInfo;
import com.miku.blog.domain.dto.MessageDTO;
import com.miku.blog.domain.param.ReceptionParam;
import com.miku.blog.domain.pojo.IpAddressesDetail;
import com.miku.blog.domain.Message;
import com.miku.blog.domain.pojo.ResponseResult;
import com.miku.blog.domain.pojo.SystemConstance;
import com.miku.blog.domain.vo.MessageVo;
import com.miku.blog.domain.vo.PageVo;
import com.miku.blog.eume.HttpStatusEnum;
import com.miku.blog.exception.SystemException;
import com.miku.blog.service.MessageService;
import com.miku.blog.mapper.MessageMapper;
import com.miku.blog.service.UserInfoService;
import com.miku.blog.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author Miku
 * @description 针对表【tb_message】的数据库操作Service实现
 * @createDate 2022-05-31 20:47:06
 */
@Slf4j
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message>
        implements MessageService {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult getMessages(Integer current,
                                      Integer size,
                                      @Nullable Integer isReview,
                                      @Nullable String keywords) {

        Page<Message> page = new Page<>(current, size);
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Objects.nonNull(isReview),Message::getIsReview,isReview)
                .like(StringUtils.hasText(keywords), Message::getNickname, keywords)
                .orderByDesc(Message::getCreateTime);
        page(page, queryWrapper);
        PageVo<Message> pageVo = new PageVo<>(page.getTotal(), page.getRecords());
        return ResponseResult.ok().setData(pageVo);
    }

    @Override
    public ResponseResult deleteMessage(Integer[] messageIdList) {
        if (!removeBatchByIds(Arrays.asList(messageIdList))) {
            return new ResponseResult(HttpStatusEnum.REMOVE_DATA_ERROR);
        }
        return ResponseResult.ok();
    }




    @Override
    public ResponseResult getMessageList() {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Message::getIsReview,SystemConstance.IS_REVIEW);
        List<Message> messageList = list(queryWrapper);
        List<MessageVo> messageVos = BeanCopyUtils.copyListByType(messageList, MessageVo.class);
        return ResponseResult.ok().setData(messageVos);
    }



    @Override
    public ResponseResult addMessage(MessageDTO messageDTO) {
        if(!StringUtils.hasText(messageDTO.getMessageContent()) || !StringUtils.hasText(messageDTO.getAvatar())
            || Objects.isNull(messageDTO.getTime())
        ){
            return new ResponseResult(HttpStatusEnum.PARAM_ERROR);
        }

        if (!StringUtils.hasText(messageDTO.getNickname())){
            messageDTO.setNickname(SystemConstance.MESSAGE_DEFAULT_NICKNAME);
        }else {
            Integer userId = SecurityUtils.getUserAuth().getId();
            UserInfo userInfo = userInfoService.getUserInfoByUserId(userId);
            messageDTO.setNickname(userInfo.getNickname());
        }

        Message message = BeanCopyUtils.copyObjectByType(messageDTO, Message.class);

        String ip = IpAddressesUtils.getIp(HttpUtils.getHttpServletRequest());
        IpAddressesDetail ipAddressesDetail = IpAddressesUtils.getIpAddressesDetail(restTemplate);
        String ipSource = UserUtils.getIpLocation(ipAddressesDetail);
        message.setIpAddress(ip)
                .setIpSource(ipSource);


        Integer isMessageReview = redisCache.getCacheHashMapValue(SystemConstance.REDIS_WEBSITE_CONFIG_REVIEW_HASH_KEY,
                SystemConstance.REDIS_WEBSITE_IS_MESSAGE_REVIEW_KEY);
        if (SystemConstance.OPEN_WEBSITE_CONFIG.equals(isMessageReview)){
            message.setIsReview(SystemConstance.NOT_REVIEW);
        }else {
            message.setIsReview(SystemConstance.IS_REVIEW);
        }


        if (!save(message)) {
            return new ResponseResult(HttpStatusEnum.INSERT_DATA_ERROR);
        }
        return ResponseResult.ok();
    }


    @Transactional
    @Override
    public ResponseResult updateMessage(ReceptionParam receptionParam) {
        List<Integer> idList = receptionParam.getIdList();
        Integer isReview = receptionParam.getIsReview();
        if (!SystemConstance.IS_REVIEW.equals(isReview) && !SystemConstance.NOT_REVIEW.equals(isReview)){
            return new ResponseResult(HttpStatusEnum.PARAM_ERROR);
        }

        LambdaUpdateWrapper<Message> updateWrapper = new LambdaUpdateWrapper<>();
        for (Integer messageId : idList) {
            updateWrapper.clear();
            updateWrapper.eq(Message::getId,messageId)
                    .set(Message::getIsReview,isReview);
            if (!update(updateWrapper)){
                throw new SystemException(HttpStatusEnum.UPDATE_DATA_ERROR);
            }
        }

        return ResponseResult.ok();
    }
}




